<?php

// Parse the parameters from the Ajax.Request

if(isset($_SERVER['HTTP_X_REQUESTED_WITH']) && $_SERVER ['HTTP_X_REQUESTED_WITH']  == 'XMLHttpRequest') {
	require('../../../../wp-config.php');
	auth_redirect();
	
	global $wpdb, $canvas;
	$parent = $_GET['parent'];
	$listitems = array();

	// Save the new values to the database
	foreach ($_GET as $key => $value) {
		$key = trim(urldecode($key));
		$value = trim(urldecode($value));

		if (($key != "_")&&($key != "parent")&&($key != "checked")) {
			if(strstr($key, 'canvaslist')) {
				$key = preg_replace('/^([0-9]*)canvaslist_/','',$key);
				if(!in_array($key, $listitems)) $listitems[] = $key;
				$$key .= $value."|";
				continue;
			}
			if($var_id = $wpdb->get_var("SELECT variable_id FROM ".$canvas->variables." WHERE variable_name = '$key' AND parent='$parent'")) {
				$wpdb->query("UPDATE ".$canvas->variables." SET value='$value' WHERE variable_name='$key' AND parent='$parent'");	 
				$updated_vars[] = $var_id;
			}
		}
	}

	// Handle list items
	if($listitems) {
		foreach($listitems as $item) {
			$new_value = preg_replace('/(\|*)$/', '', $$item);
			$wpdb->query("UPDATE ".$canvas->variables." SET value='$new_value' WHERE variable_name='$item' AND parent='$parent'");
		}
	}

	// Save any values that weren't passed in the GET string, eg. empty checkboxes
	$variables = $wpdb->get_results("SELECT variable_id,type FROM ".$canvas->variables." WHERE parent='$parent' AND variable_id NOT IN ('".implode("','", $updated_vars)."')");
	
	if (!empty($variables)) {
		foreach ($variables as $variable) {
			// Here's where we define what the default "false" value is for each variable type
			switch ($variable->type) {
				case "Boolean":
					$wpdb->query("UPDATE ".$canvas->variables." SET value='0' WHERE variable_id='$variable->variable_id'");
				break;
			}
		}
	}
}
?>